package com.hk.common.utils;

import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;

import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * @author zhangyu
 * @date 2019-11-04
 */
public class ResponseUtils {

    private static final Logger log = LoggerFactory.getLogger(ResponseUtils.class);

    public static HttpHeaders headers = new HttpHeaders();

    static{
        headers.add("Content-Type", "application/json; charset=utf-8");
    }

    public static HttpHeaders getDefaultHeaders() {
        HttpHeaders h = new HttpHeaders();
        h.add("Content-Type", "application/json; charset=utf-8");
        return h;
    }


    /**
     * response返回
     * @param response
     * @param entity
     */
    public static void write(ServletResponse response, ResponseEntity entity){

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        try {
            response.getWriter().print(JSONObject.toJSONString(entity));
        } catch (IOException e) {
            log.error("tryReturn :"+e.getMessage()+",",e);
        }

    }


    public static ResponseEntity<Object> tryReturn(String errorMsg,DataInterface dataApi){
        ResponseEntity<Object> re;
        try{
            re = ResponseEntity.ok(dataApi.getData());
        }catch (Exception e){
            log.error("tryReturn :"+errorMsg+",",e);
            re = ResponseEntity.status(500).body(errorMsg+" 异常:"+e.getMessage());
        }
        return re;
    }

    /**
     * Data接口
     */
    public interface DataInterface{
        /**
         * 获取数据
         * @return
         * @throws Exception
         */
        Object getData() throws Exception;
    }
}
